//
//  HPFunctionViewController.m
//  HPZZTong
//
//  Created by handpay on 14-4-3.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPFunctionViewController.h"
//#import "ZZTBalanceEnquiry.h" // mcm
//#import "POSUIEngine.h" // mcm
#import "RFCSNValidatorController.h"
#import "RFPOSUIEngine.h" // mcm new
#import <HandPaySwiperModule/HandPaySwiperModule.h>
#import <HandPaySwiperModule/HPSwiperResult.h>
#import <HandPaySwiperModule/SwipeInfo.h>

@interface HPFunctionViewController ()<HPSwiperContextDelegate>{
    
//ZZT_FOR_ADDRESS
    IBOutlet UITextField *latituTextField;
    IBOutlet UITextField *longtitudeTextField;
    IBOutlet UIView *addrView;
//
    // mcm new
    HPSwiperContext* posContext;
    NSInteger processingType;
    RFPOSUIEngine* posProcessStateController;
}

//@property (retain,nonatomic) ZZTBalanceEnquiry * balanceProcess; // mcm
@property(nonatomic, retain) POSProcess* balanceProcess; // mcm
@property (nonatomic)FunctionType functionType;

// ZZT_FOR_ADDRESS
- (IBAction)saveClick:(id)sender;
//

@end

@implementation HPFunctionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.showBackButton = NO;
        self.hideBottomBar = NO;
        posContext = [HPSwiperContext sharedInstance]; // mcm new
        processingType = -1; // mcm new
    }
    return self;
}

-(void)choiseYourDevice:(NSArray *)devices
{   // TODO: not complete.
    NSException* notImplementException = [NSException exceptionWithName:@"NotImplementException"
                                                                 reason:@"invoke not implement protocal selector"
                                                               userInfo:nil];
    @throw notImplementException;
}

- (void)viewDidLoad
{
    self.title = @"功能";
    [super viewDidLoad];
#if ZZT_FOR_ADDRESS
    addrView.hidden = NO;
#endif
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [ZZT_UIENG hideNavigationBar:NO];
    self.tabBarController.tabBar.hidden = NO;
//    [self hideTabBar:NO];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [ZZT_UIENG hideNavigationBar:NO];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
// ZZT_FOR_ADDRESS
    [addrView release];
    [longtitudeTextField release];
    [latituTextField release];
    if (posProcessStateController)
        [posProcessStateController release];
//
    [super dealloc];
}
- (void)viewDidUnload {
    [super viewDidUnload];
}

- (IBAction)accountClick:(id)sender {
    
    [HPUIENG showScreen:SCR_CM_TRANS_RECORD params:@{@"appCode": @"1"}];
}

- (void)showFastTrans{
    [HPUIENG showScreen:SCR_FAST_TRANSFER];
}

- (IBAction)fastTransClick:(id)sender
{
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    if (![zzt checkAccountStatus:FunctionTypeFastTransfer])
        return;
    // mcm
//    [SWIPERENG selectSwiperAndGetCsn:^(HPSwiperResult *swiperResult) {
//        [CSNValidator checkCSNStatus:^(HPSwiperResult *swiperResult) {
//            if (swiperResult.isSuccess)
//            {
//                [self showFastTrans];
//            }
//        } autoTip:YES];
//
//    } isShow:NO];
    // mcm new
    processingType =  FunctionTypeFastTransfer;
    [self selectSwipeAndGetCsn];
}

- (IBAction)balanceClick:(id)sender
{
    if (![ZZT_CLIENG checkAccountStatus:FunctionTypeBalance])
        return;
    // mcm
//    [SWIPERENG selectSwiperAndGetCsn:^(HPSwiperResult *swiperResult) {
//        _balanceProcess = [[ZZTBalanceEnquiry alloc] init];
//        [_balanceProcess beginWithDelegate:self];
//    } isShow:NO];
    
    // mcm new
    processingType = FunctionTypeBalance;
    [self selectSwipeAndGetCsn];
}

- (void)selectApplication:(id)process result:(HPSwiperResult *)result{
    NSArray* array = (NSArray*)result.value;
    
    NSMutableArray* mutArray = [NSMutableArray array];
    
    for (int i = 0; i<array.count; i++) {
        NSString* strData = [array objectAtIndex:i];
        if (![NSString isNilOrEmpty:strData]) {
            
            NSString* strTemp = [strData uppercaseString];
            NSString* strName = nil;
            
            NSRange range = [strTemp rangeOfString:@"CREDIT"];
            if (range.length != 0) {
                strName = @"信用卡";
            }
            range = [strTemp rangeOfString:@"DEBIT"];
            if (range.length != 0) {
                strName = @"借记卡";
            }
            
            if (![NSString isNilOrEmpty:strName]) {
                [mutArray addObject:@[strName,strData,[NSNumber numberWithInt:i]]];
            }
        }
    }
    
    [posProcessStateController processSelectApp:mutArray]; // mcm new
//    [POSUIENG processSelectApp:mutArray]; // mcm
}
- (void)process:(id)process finishedWithResult:(HPSwiperResult *)result
{
    if (!result.isSuccess)
    {
//        [POSUIEngine processFailed:process result:result]; // mcm
        [RFPOSUIEngine processFailed:process result:result]; // mcm new
    }
    else
    {
        [self sendBalanceReq];
        _balanceProcess = nil;
    }
}

-(void)sendBalanceReq
{
    RFCSNValidatorController* validator = [RFCSNValidatorController sharedInstance];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:validator.location forKey:KEY_LOCATION];
    [params setObject:validator.address forKey:KEY_ADDRESS];
    
    if (![NSString isNilOrEmpty:_balanceProcess.encAccount])
        [params setObject:self.balanceProcess.encAccount forKey:@"cardNo"];
    else if(![NSString isNilOrEmpty:self.balanceProcess.swipeInfo.encAccount])
        [params setObject:_balanceProcess.swipeInfo.encAccount forKey:@"cardNo"];
    
    if (![NSString isNilOrEmpty:self.balanceProcess.encPin])
        [params setObject:self.balanceProcess.encPin forKey:@"pin"];
    else if(![NSString isNilOrEmpty:self.balanceProcess.swipeInfo.encPin])
        [params setObject:self.balanceProcess.swipeInfo.encPin forKey:@"pin"];
    
    [params setObject:self.balanceProcess.factor forKey:@"factor"];
    [params setObject:DES_ENC(self.balanceProcess.csn) forKey:@"csn"];
    [params setObject:[ZZT_CLIENG getChannel] forKey:KEY_CHANNEL];
    [params setObject:[ZZT_CLIENG getChannel] forKey:@"channel"];
    [params setObject:DES_ENC(ZZT_CLIENG.accountInfo.account) forKey:@"account"];
    if (_balanceProcess.swipeInfo.icMode)
    {
        if (_balanceProcess.swipeInfo.icNumber.length > 0)
        {
            [params setObject:_balanceProcess.swipeInfo.icNumber forKey:@"ICNumber"];
        }
        [params setObject:_balanceProcess.swipeInfo.dcData forKey:@"DCData"];
        [params setObject:_balanceProcess.encMac forKey:@"mac"];
    }
    if (![NSString isNilOrEmpty:_balanceProcess.swipeInfo.encTrack2]) {
        [params setObject:_balanceProcess.swipeInfo.encTrack2 forKey:@"track2"];
    }
    if (![NSString isNilOrEmpty:_balanceProcess.swipeInfo.dynamicKey]) {
        [params setObject:_balanceProcess.swipeInfo.dynamicKey forKey:@"dynamicKeyData"];
    }
    [ZZT_CLIENG.netEngine sendRequest:NET_ACTION_BALANCE withParams:params withDelegate:self withAlertFlag:NO];
    [ZZT_CLIENG.uiEngine showNetWaiting];
}

//- (void)sendBalanceReq
//{
//    NSMutableDictionary * params = [NSMutableDictionary dictionary];
//    [params setObject:[CSNValidator getLocation] forKey:KEY_LOCATION];
//    [params setObject:[CSNValidator getAddress] forKey:KEY_ADDRESS];
//    if (![NSString isNilOrEmpty:_balanceProcess.encAccount]) {
//        [params setObject:_balanceProcess.encAccount forKey:@"cardNo"];
//    }else if(![NSString isNilOrEmpty:_balanceProcess.swipeInfo.encAccount]){
//        [params setObject:_balanceProcess.swipeInfo.encAccount forKey:@"cardNo"];
//    }
//    if (![NSString isNilOrEmpty:_balanceProcess.encPin]) {
//        [params setObject:_balanceProcess.encPin forKey:@"pin"];
//    }else if(![NSString isNilOrEmpty:_balanceProcess.swipeInfo.encPin]){
//        [params setObject:_balanceProcess.swipeInfo.encPin forKey:@"pin"];
//    }
//    
//    [params setObject:_balanceProcess.factor forKey:@"factor"];
//    [params setObject:DES_ENC(_balanceProcess.csn) forKey:@"csn"];
//    [params setObject:[ZZT_CLIENG getChannel] forKey:KEY_CHANNEL];
//    [params setObject:[ZZT_CLIENG getChannel] forKey:@"channel"];
//    [params setObject:DES_ENC(ZZT_CLIENG.accountInfo.account) forKey:@"account"];
//    if (_balanceProcess.swipeInfo.icMode)
//    {
//        if (_balanceProcess.swipeInfo.icNumber.length > 0)
//        {
//            [params setObject:_balanceProcess.swipeInfo.icNumber forKey:@"ICNumber"];
//        }
//        [params setObject:_balanceProcess.swipeInfo.dcData forKey:@"DCData"];
//        [params setObject:_balanceProcess.encMac forKey:@"mac"];
//    }
//    if (![NSString isNilOrEmpty:_balanceProcess.swipeInfo.encTrack2]) {
//        [params setObject:_balanceProcess.swipeInfo.encTrack2 forKey:@"track2"];
//    }
//    if (![NSString isNilOrEmpty:_balanceProcess.swipeInfo.dynamicKey]) {
//        [params setObject:_balanceProcess.swipeInfo.dynamicKey forKey:@"dynamicKeyData"];
//    }
//    [ZZT_CLIENG.netEngine sendRequest:NET_ACTION_BALANCE withParams:params withDelegate:self withAlertFlag:NO];
//    [ZZT_CLIENG.uiEngine showNetWaiting];
//}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    if ([action isEqualToString:NET_ACTION_BALANCE]) {
        [HPUIENG popScreen];
        [HPUIENG showAlert:msg];
    }
}
- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    [HPUIENG removeWaiting];
   if ([action isEqualToString:NET_ACTION_BALANCE]){
        [self doBalanceCallback:respData];
    }
}
- (void)doBalanceCallback:(NSDictionary*)respData{
  
    [HPUIENG removeWaiting];
    [HPUIENG showScreen:SCR_BALANCE_RESULT params:respData];
}

// ZZT_FOR_ADDRESS
- (IBAction)saveClick:(id)sender {
    if (![NSString isNilOrEmpty:longtitudeTextField.text] && ![NSString isNilOrEmpty:latituTextField.text]) {
        [HPCLIENTENG SaveGlobalData:longtitudeTextField.text withKey:@"longtitude"];
        [HPCLIENTENG SaveGlobalData:latituTextField.text withKey:@"Latitude"];
        
        [HPUIENG showAlert:@"保存成功!"];
    }else{
        [HPCLIENTENG SaveGlobalData:nil withKey:@"longtitude"];
        [HPCLIENTENG SaveGlobalData:nil withKey:@"Latitude"];
        
        [HPUIENG showAlert:@"清除成功!"];
    }
}

#pragma mark - HPSwiperContextDelegate

// mcm new
-(void)selectSwipeAndGetCsn
{
    if (posContext.connectedDeviceCSN.length)
        [self swiperCsnDidChange:posContext.connectedDeviceCSN];
    else
    {
        [posContext addDelegate:self];
        [HPUIENG showScreen:SCR_SWIPER_SELECT];
    }
}

// mcm new
-(void)swiperCsnDidChange:(NSString*)didChangeCsn
{
    [posContext removeDelegate:self];
    if ([self isConnectSwipeFaild])
        return;
    
    RFCSNValidatorController* validator = [RFCSNValidatorController sharedInstance];
    [validator validateCSNComplete:^(BOOL succ, NSString *errInfo) {
        [self continueWithValidate:succ errorMessge:errInfo];
    } autoTip:YES];
}

-(void)continueWithValidate:(BOOL)isValide errorMessge:(NSString*)message
{
    if (processingType == FunctionTypeFastTransfer)
        [self showFastTrans];
    else if(processingType == FunctionTypeBalance)
    {
        self.balanceProcess = [posContext processorWithBindingInfo:nil businessType:HPPOSBusinessTypeBalance];
        if (posProcessStateController)
            [posProcessStateController release];
        posProcessStateController = [[RFPOSUIEngine alloc] initWithPOSProcess:self.balanceProcess];
        [self.balanceProcess beginWithDelegate:self];
    }
}

-(BOOL)isConnectSwipeFaild
{
    id<HPSwipeServiceProtocal> swipeService = [HPSwiperContext sharedInstance].avaliableService;
    NSString* alertViewMessage = nil;
    if (!swipeService || swipeService.swiperConnectState == SwiperStateNoDeviceDected || swipeService.csn.length == 0)
        alertViewMessage = @"请插入刷卡器";
    else if(swipeService.swiperConnectState == SwiperStateLowBattery)
        alertViewMessage = TipsLowBattery;
    
    BOOL hasErrInfo = alertViewMessage != nil;
    if (hasErrInfo)
        [HPUIENG showAlert:@"请插入刷卡器"];
    return hasErrInfo;
}

@end
